package com.cg.test.numsum;

import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class IntegerSumForkJoinTask extends RecursiveTask<Integer> {

    private static final int threshold = 2;
    private int start;
    private int end;

    public IntegerSumForkJoinTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //如果任务足够小就计算任务
        boolean canCompute = (end - start) <= threshold;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            // 如果任务大于阈值，就分裂成两个子任务计算
            int middle = (start + end) / 2;
            IntegerSumForkJoinTask leftTask = new IntegerSumForkJoinTask(start, middle);
            IntegerSumForkJoinTask rightTask = new IntegerSumForkJoinTask(middle + 1, end);

            // 执行子任务
            leftTask.fork();
            rightTask.fork();

            // 等待任务执行结束合并其结果
            int leftResult = leftTask.join();
            int rightResult = rightTask.join();

            // 合并子任务
            sum = leftResult + rightResult;
        }
        return sum;
    }

    public static void integerSum(int start, int end) {
        long l = System.currentTimeMillis();
        int sum = 0;
        for (int i = start; i <= end; i++) {
            sum += i;
        }
        System.out.println("叠加耗时:" + (System.currentTimeMillis() - l) + " 结果：" + sum);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        IntegerSumForkJoinTask task = new IntegerSumForkJoinTask(1, 100000000);
        long l = System.currentTimeMillis();
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        System.out.println("fork/join耗时：" + (System.currentTimeMillis() - l) + " 结果：" + submit.get());

        integerSum(1, 100000000);
    }
}
